﻿/*****************************************************
 * 本类库的核心系 JNTemplate
 * (C) JNTemplate 2011
 * 作者：翅膀的初衷 QQ:4585839
 * 网址：http://www.JiNianNet.com
 *****************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace JinianNet.JNTemplate.Process.Element
{
    public class ForeachTag : CompositeTag
    {
        private List<Token> _element;

        public ForeachTag(string text)
            : base(TokenKind.Foreach, text)
        {
            this._element = new List<Token>();
        }
        /// <summary>
        /// 循环实体
        /// </summary>
        public List<Token> Element
        {
            get { return this._element; }
            set { this._element = value; }
        }
        private string _source;
        /// <summary>
        /// 数据源
        /// </summary>
        public string Source
        {
            get { return this._source; }
            set { this._source = value; }
        }
        private string _entity;

        /// <summary>
        /// 循环实体
        /// </summary>
        public string Entity
        {
            get { return this._entity; }
            set { this._entity = value; }
        }

        public override void Parser(VariableScope varScope, System.IO.TextWriter write)
        {
            if (string.IsNullOrEmpty(this._source))
            {
                write.Write("循环标签 数据源未定义");
                return;
            }
            if (string.IsNullOrEmpty(this._entity))
            {
                write.Write("循环标签 循环对象未定义");
                return;
            }

            IEnumerable dataSource = varScope.ToIEnumerable(new VariableTag(this._source).Parser(varScope));

            if (dataSource != null)
            {
                IEnumerator ienum = dataSource.GetEnumerator();
                VariableScope scope = new VariableScope(varScope, false);
                int i = 0;
                while (ienum.MoveNext())
                {
                    scope[this._entity] = ienum.Current;
                    i++;
                    scope["ForeachIndex"] = i;
                    foreach (Token token in this._element)
                        write.Write(token.Parser(scope));
                }
                scope.Clear(false);

            }
        }

    }
}
